﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Web.Mvc;
using Confcloud.Email.Templates;
using Smarly.Core;
using Smarly.Core.Database;

namespace Smarly.Bussines.Model.Account
{
	public class UpdatePassword : ModelStateObject
	{
		[Required(ErrorMessage = "Поле не заполнено")]
		[DatabaseValidation("UnknownRestoreHashCode", "Значение кода не корректно")]
		[DatabaseValidation("RestoreHashCodeExpired", "Необходимо повторить процедуру востановления")]
		public string HashCode { get; set; }

		[Required(ErrorMessage = "Поле не заполнено")]
		[StringLength(32, MinimumLength = 6, ErrorMessage = "Минимальная длина 6 символов")]
		[RegularExpression(@"^\w+$", ErrorMessage = "Должен содержать только цифры, латинские буквы и подчеркивание")]
		public string Password { get; set; }

/*
		[RegularExpression(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$", ErrorMessage = "Должен содержать минимум одну цифру, одну большую букву и одну маленькую букву")]
*/
		[Compare("Password", ErrorMessage = "Пароли не совпадают")]
		public string RepeatPassword { get; set; }

		public string Email { get; set; }

		public UpdatePassword GetEmail()
		{
			SqlRepository.ExecuteProcedureReader("UserRestore_GetEmail",
																					 new List<SpParam>
			                                     	{
			                                     		new SpParam {Name = "@restoreHashCode", Type = DbType.String, Value = HashCode},
			                                     	},
																					 OnSqlInfoMessage,
																					 reader => ModelState.IsValid ? ReadEmailPut(reader) : ReadInvalideModelStateEmailPut(reader));
			return this;
		}

		public UpdatePassword Put()
		{
			GetEmail();

			if (ModelState.IsValid)
			{
				Password pass = new Password() { PasswordString = Password };
				pass.EncodePassword();

				string hash = pass.PasswordHash;
				string salt = pass.PasswordSalt;

				SqlRepository.ExecuteProcedureReader("User_UpdatePassword",
																						 new List<SpParam>
			                                     	{
			                                     		new SpParam {Name = "@email", Type = DbType.String, Value = Email},
			                                     		new SpParam {Name = "@passwordHash", Type = DbType.String, Value = hash},
			                                     		new SpParam {Name = "@passwordSalt", Type = DbType.String, Value = salt},
			                                     	},
																						 OnSqlInfoMessage,
																					 reader =>
																					 	{
																					 		HashCode = null;
																						 while (reader.Read())
																						 {
																							 this.HashCode = reader.GetString("UserHashCode");
																						 }
																						 return this;
																					 });

				new PasswordChangedEmail(Email).Post();

			}
			return this;
		}

		public UpdatePassword ReadEmailPut(IDataReader reader)
		{
			while (reader.Read())
			{
				this.Email = reader.GetString("Email");
			}
			return this;
		}

		public UpdatePassword ReadInvalideModelStateEmailPut(IDataReader reader)
		{
			return this;
		}
	}
}